import { LogoutOutlined, SettingOutlined, UserOutlined, EditOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin, Modal, Input, Form, message } from 'antd';
import { FormInstance } from 'antd/lib/form';
import React from 'react';
import { history, ConnectProps, connect } from 'umi';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { updatePassword } from '@/pages/system/service';

export interface GlobalHeaderRightProps extends Partial<ConnectProps> {
  currentUser?: CurrentUser;
  menu?: boolean;
}

class AvatarDropdown extends React.Component<GlobalHeaderRightProps> {
  state = {
    changePasswordModalvisible: false,
  };

  onMenuClick = (event: {
    key: React.Key;
    keyPath: React.Key[];
    item: React.ReactInstance;
    domEvent: React.MouseEvent<HTMLElement>;
  }) => {
    const { key } = event;

    if (key === 'logout') {
      const { dispatch } = this.props;

      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }

      return;
    }

    if (key === 'changePassword') {
      this.setState({ changePasswordModalvisible: true });
      return;
    }

    history.push(`/account/${key}`);
  };

  //表单的引用
  formRef = React.createRef<FormInstance>();

  okHandle = () => {
    const fieldsValue = this.formRef.current?.getFieldsValue();
    const newPassword = this.formRef.current?.getFieldValue('newPassword');
    const oldPassword = this.formRef.current?.getFieldValue('oldPassword');

    updatePassword({ newPassword: newPassword, oldPassword: oldPassword }).then(({ code, msg }) => {
      if (code === 0) {
        message.success('修改成功，请重新登录！');
        this.setState({ changePasswordModalvisible: false });
        this.gotoLogin();
      } else {
        message.error('重置密码失败，' + msg);
      }
    });
  };

  gotoLogin = () => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'login/logout',
      });
    }
    // history.push(`/user/login`);
  };

  cancleHandle = () => {
    // 重置表单里的密码
    this.formRef.current!.resetFields();
    this.setState({ changePasswordModalvisible: false });
  };

  render(): React.ReactNode {
    const {
      currentUser = {
        avatar: '',
        userName: '',
      },
      menu,
    } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key="center">
            <UserOutlined />
            个人中心
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key="settings">
            <SettingOutlined />
            个人设置
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}

        <Menu.Item key="changePassword">
          {' '}
          <EditOutlined />
          修改密码
        </Menu.Item>

        <Menu.Divider />

        <Menu.Item key="logout">
          <LogoutOutlined />
          退出登录
        </Menu.Item>
      </Menu>
    );

    return (
      <div>
        {currentUser && currentUser.userName ? (
          <HeaderDropdown overlay={menuHeaderDropdown}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar
                size="small"
                className={styles.avatar}
                src={currentUser.avatar}
                alt="avatar"
              />
              <span className={`${styles.name} anticon`}>{currentUser.userName}</span>
            </span>
          </HeaderDropdown>
        ) : (
          <span className={`${styles.action} ${styles.account}`}>
            <Spin
              size="small"
              style={{
                marginLeft: 8,
                marginRight: 8,
              }}
            />
          </span>
        )}
        <Modal
          title="修改密码"
          visible={this.state.changePasswordModalvisible}
          onOk={() => this.okHandle()}
          onCancel={() => this.cancleHandle()}
          maskClosable={false}
          okText="确认"
          cancelText="取消"
        >
          <Form ref={this.formRef}>
            <Form.Item
              label="原密码"
              name="oldPassword"
              rules={[{ required: true, message: '密码不能为空！' }]}
            >
              <Input.Password placeholder="请输入原密码" />
            </Form.Item>
            <Form.Item
              label="新密码"
              name="newPassword"
              hasFeedback
              rules={[
                { required: true, message: '密码不能为空！' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    // 校验密码强度
                    // 1. 必须同时包含大写字母、小写字母和数字，三种组合
                    // 2. 长度在8-30之间
                    const passwordReg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/;

                    if (!passwordReg.test(value)) {
                      return Promise.reject('密码必须同时包含大写字母、小写字母和数字！');
                    }
                    if (value.length < 8 || value.length > 30) {
                      return Promise.reject('密码长度8-30位！');
                    }
                    return Promise.resolve();
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请输入新密码" />
            </Form.Item>
            <Form.Item
              label="重复输入新密码"
              name="repeatNewPassword"
              dependencies={['newPassword']}
              hasFeedback
              rules={[
                { required: true, message: '密码不能为空！' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject('两次输入不一致！');
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请重复输入新密码" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
